﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.tanlingyun.baojia.Entity;
using com.tanlingyun.ViewModel;
using com.tanlingyun.helper;
using FluentData;

namespace com.tanlingyun.DbServices
{
    public class UserService:BaseService
    {
        /// <summary>
        /// 验证用户token
        /// </summary>
        /// <param name="id"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public OperateResult<User> ValidateUser(int id,string token)
        {
            User entityUser = GetUser(id);
            if (entityUser == null || entityUser.isgrant != 1)
                return new OperateResult<User>() { code = ResultCode.UnAuthorized, message = "用户不存在或者未授权!" };
            UserToken entityToken = GetUserToken(id);
            if (entityToken == null || entityToken.expired_time < DateTime.Now)
                return new OperateResult<User>() { code = ResultCode.UnAuthorized,message = "账号已过期，请重新登录!" };
            //验证ip
            return new OperateResult<User>() { code = ResultCode.Success, data = entityUser };
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public OperateResult<User> CheckUser(string username,string password)
        {
            User entityUser = GetUser(username);
            if (entityUser == null || entityUser.status!=1)
                return new OperateResult<User>() { code = ResultCode.UnAuthorized, message = "用户不存在!" };
            if (!entityUser.password.Equals(password))
                return new OperateResult<User>() { code = ResultCode.UnAuthorized, message = "密码错误!" };
            if (entityUser.isgrant != 1)
                return new OperateResult<User>() { code = ResultCode.UnAuthorized,message = "未授权，请联系系统管理员!" };
            
            //验证管理员状态
            if(entityUser.parentid>0)
            {
                User parentUser = GetUser(entityUser.parentid);
                if (parentUser == null || parentUser.status != 1)
                    return new OperateResult<User>() { code = ResultCode.Failed,message = "您的管理员账号不存在，无法登录！" };
                if (parentUser.isgrant != 1)
                    return new OperateResult<User>() { code = ResultCode.Failed,message = "您的管理员账号已被取消授权，请联系管理员。" };
            }

            //生成新的token
            string str_token = Guid.NewGuid().ToString().Replace("-","");
            UserToken token = GetUserToken(entityUser.id);
            if(token == null)
            {
                token = new UserToken() {
                    user_id  = entityUser.id,
                    token = str_token,
                    refresh_time = DateTime.Now,
                    expired_time = DateTime.Now.AddMinutes(helper.UtilityHelper.GetIntConfig("token_expired"))
                };
                if (db.Insert<UserToken>("UserToken", token).AutoMap(x=>x.id).Execute() <= 0)
                    return new OperateResult<User>() { code = ResultCode.Failed,message = "登录失败!" };
            }else
            {
                token.refresh_time = DateTime.Now;
                token.expired_time = token.refresh_time.AddMinutes(helper.UtilityHelper.GetIntConfig("token_expired"));
                token.token = str_token;
                if(db.Update<UserToken>("UserToken", token).AutoMap(x=>x.id).Where(x=>x.id).Execute()<=0)
                    return new OperateResult<User>() { code = ResultCode.Failed, message = "登录失败!" };
            }
            CookieHelper.Add(".user", helper.UtilityHelper.EncodeToBase64(entityUser.id + ":" + str_token), true);
            return new OperateResult<User>() { code = ResultCode.Success };
        }

        /// <summary>
        /// 注册/添加用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public OperateResult Register(string username,string password,string name,string userid = null,ELevelType type = ELevelType.Manager)
        {
            User entityUser = GetUser(username);
            if (entityUser != null)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("用户名：{0}已经存在!", username) };
            entityUser = new User() {
                name = name,
                password = password,
                username = username,
                isgrant = 0,
                userid  = userid,
                level_type = (int)type,
                status = 1
            };
            if (db.Insert<User>("User", entityUser).AutoMap(x => x.id).ExecuteReturnLastId<int>() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed,message = "注册失败!" };
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public OperateResult AddUser(int user_id,User user)
        {
            User entityUser = GetUser(user_id);
            if (entityUser == null || entityUser.isgrant != 1 || entityUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "身份信息错误，无法进行操作！" };
            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed,message = "操作员不可以进行此操作！" };
            if (entityUser.level_type == (int)ELevelType.Manager && user.level_type != (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed,message = "管理员只可以添加操作员！" };

            User addUser = GetUser(user.username);
            if (addUser != null && addUser.status == 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("用户名{0}已经存在！", user.username) };

            user.parentid = user_id;
            user.status = 1;

            if (user.level_type == (int)ELevelType.Operator)
                user.isgrant = 1;

            if (db.Insert<User>("User", user).AutoMap(x => x.id).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed,message = "添加失败!" };
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="upd_user"></param>
        /// <param name="curPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public OperateResult ChangePassword(int user_id,int upd_user, string newPwd, string curPwd = "")
        {
            User entityUser = GetUser(user_id);
            if (entityUser == null || entityUser.isgrant != 1 || entityUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户身份错误，无法进行操作！" };
            if (!entityUser.password.Equals(curPwd))
                return new OperateResult() { code = ResultCode.Failed,message = "当前用户密码错误！" };

            User updateUser = GetUser(upd_user);
            if (updateUser == null || updateUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "修改的用户不存在!" };

            //验证权限
            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "操作员无法进行此操作！" };
            if (entityUser.level_type == (int)ELevelType.Manager && updateUser.level_type != (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "管理员没有权限完成此操作!" };
            else if (entityUser.level_type == (int)ELevelType.Manager && updateUser.level_type == (int)ELevelType.Operator && entityUser.id != updateUser.parentid)
                return new OperateResult() { code = ResultCode.Failed, message = "该操作员不属于您，修改失败！" };

            updateUser.password = newPwd;

            if (db.Update<User>("User", updateUser).AutoMap(x => x.id).Where(x => x.id).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed,message = "密码修改失败!" };
        }

        /// <summary>
        /// 授权/取消授权
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="grt_user"></param>
        /// <param name="isgrant">1-授权，0-取消授权</param>
        /// <returns></returns>
        public OperateResult GrantUser(int user_id,int grt_user,int isgrant = 1)
        {
            User entityUser = GetUser(user_id);
            if (entityUser == null || entityUser.isgrant != 1 || entityUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户身份错误，无法进行操作！" };

            User grant_user = GetUser(grt_user);
            if (grant_user == null || grant_user.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "授权的用户不存在!" };

            //验证删除权限
            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "操作员无法进行此操作！" };
            if (entityUser.level_type == (int)ELevelType.Manager && grant_user.level_type != (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "管理员没有权限完成此操作!" };

            if (grant_user.level_type == (int)ELevelType.Admin)
                return new OperateResult() { code = ResultCode.Failed,message = "超级管理员禁止更改！" };

            grant_user.isgrant = isgrant;

            if (db.Update<User>("User", grant_user).Column(x => x.isgrant).Where(x => x.id).Execute() > 0)
            {
                
                return new OperateResult() { code = ResultCode.Success };
            }
            return new OperateResult() { code = ResultCode.Failed,message = "授权信息修改失败!" };
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="manager_id"></param>
        /// <returns></returns>
        public OperateResult InitManagerData(int user_id,int manager_id)
        {
            
            return new OperateResult() { };
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="del_user"></param>
        /// <returns></returns>
        public OperateResult DeleteUser(int user_id,int del_user)
        {
            User entityUser = GetUser(user_id);
            if (entityUser == null || entityUser.isgrant != 1 || entityUser.status!=1)
                return new OperateResult() { code = ResultCode.Failed,message = "用户身份错误，无法进行操作！" };
            
            User DeleteUser = GetUser(del_user);
            if (DeleteUser == null || DeleteUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed,message = "删除的用户不存在!" };

            //验证删除权限
            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "操作员无法进行此操作！" };
            if (entityUser.level_type == (int)ELevelType.Manager && DeleteUser.level_type != (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "管理员没有权限完成此操作!" };
            else if (entityUser.level_type == (int)ELevelType.Manager && DeleteUser.level_type == (int)ELevelType.Operator && entityUser.id != DeleteUser.parentid)
                return new OperateResult() { code = ResultCode.Failed,message = "该操作员不属于您，删除失败！" };

            DeleteUser.status = 0;
            if (db.Update<User>("User", DeleteUser).Column(x => x.status).Where(x => x.id).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            //if (db.Delete<User>("User", DeleteUser).Where(x => x.id).Execute() > 0)
            //    return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed,message = "用户删除失败!" };
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="updUser"></param>
        /// <returns></returns>
        public OperateResult UpdateUser(int user_id,User updUser)
        {
            User entityUser = GetUser(user_id);
            if (entityUser == null || entityUser.isgrant != 1 || entityUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户身份错误，无法进行操作！" };

            User updateEntity = GetUser(updUser.id);
            if (updateEntity == null || updateEntity.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "修改的用户不存在!" };

            //验证删除权限
            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "操作员无法进行此操作！" };
            if (entityUser.level_type == (int)ELevelType.Manager && updateEntity.level_type != (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "管理员没有权限完成此操作!" };

            updateEntity.userid = updUser.userid;
            updateEntity.username = updUser.username;
            updateEntity.name = updUser.name;

            if (db.Update<User>("User", updateEntity).Column(x => x.userid).Column(x => x.username).Column(x => x.name).Where(x => x.id).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };

            return new OperateResult() { code = ResultCode.Failed,message = "用户信息修改失败!" };
        }
        
        /// <summary>
        /// 获取用户分页
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="search"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="level">获取用户类型</param>
        /// <returns></returns>
        public PageInfo<V_list_user> GetUserPage(int user_id,string search = "",int PageIndex = 1,int PageSize = 10,ViewModel.ELevelType level = ELevelType.Operator)
        {

            PageInfo<V_list_user> puser = new PageInfo<V_list_user>() {
                Fields = "*,(select name from User where id=a.parentid) as parent_name",
                TableName = "User a",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "ID desc"
            };
            string where = "status = 1";
            User entityUser = GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant!=1)
                return puser;

            if (entityUser.level_type == (int)ELevelType.Operator)
                return puser;

            if(entityUser.level_type == (int)ELevelType.Manager)
            {
                if (level == ELevelType.Operator)
                    where += " and parentid=" + entityUser.id + " and level_type=" + (int)ELevelType.Operator;
                else
                    return puser;
            }else if(entityUser.level_type == (int)ELevelType.Admin)
            {
                where += " and level_type=" + (int)level;
            }

            if (!string.IsNullOrWhiteSpace(search))
                where += " and (userid like '%"+search+"%' or name like '%"+search+"%' or username like '%"+search+"%' )";
            puser.Where = where;
            return GetPageInfo<V_list_user>(puser);
        }

        /// <summary>
        /// 通过编号获取用户token
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserToken GetToken(int id)
        {
            return db.Sql("select * from UserToken where id  = @0", id).QuerySingle<UserToken>();
        }

        /// <summary>
        /// 通过用户编号获取用户token
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public UserToken GetUserToken(int user_id)
        {
            return db.Sql("select * from UserToken where user_id  = @0", user_id).QuerySingle<UserToken>();
        }

        public User GetUser(string username)
        {
            return db.Sql("select * from User where username=@0 order by status desc", username).QuerySingle<User>();
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public User GetUser(int id)
        {
            return db.Sql("select * from  User where id=@0  order by status desc", id).QuerySingle<User>();
        }

        public OperateResult InitUserAllData(int user_id,int init_user)
        {

            using (IDbContext newdb = db.UseTransaction(true))
            {
                
            }

            return new OperateResult() { code = ResultCode.Failed,message = "数据初始化失败！" };
        }

    }
}
